"use client"

import { createFlag } from "@/api/flag/add";
import { selectUserDetail } from "@/lib/features/login/loginSlice";
import { useAppDispatch, useAppSelector } from "@/lib/hooks";
import { Popover, PopoverTrigger, PopoverContent } from "@heroui/popover";
import { AddFlagParams } from "@/type/flag";
// import Flag from "@/type/flag";
import {
    Modal,
    ModalContent,
    ModalHeader,
    ModalBody,
    ModalFooter,
    Button,
    Textarea,
    ButtonGroup,
    Input,
    Select,
    SelectItem,
    TimeInput,
    CheckboxGroup,
    Checkbox,
} from "@nextui-org/react";
import { TimeValue } from '@react-types/datepicker';
import { Time } from '@internationalized/date';

import { useState } from "react";
import toast from "react-hot-toast";
import { getRandomEmoji, unicodeToEmoji } from "@/utils/randomemoji";
import { selectFlagDetail, updateFlagData } from "@/lib/features/flag/flagSlice";

export const ClockCircleLinearIcon = (props: React.SVGProps<SVGSVGElement>) => {
    return (
        <svg
            aria-hidden="true"
            fill="none"
            focusable="false"
            height="1em"
            role="presentation"
            viewBox="0 0 24 24"
            width="1em"
            {...props}
        >
            <g fill="none" stroke="currentColor" strokeWidth="1.5">
                <circle cx="12" cy="12" r="10" />
                <path d="M12 8v4l2.5 2.5" strokeLinecap="round" strokeLinejoin="round" />
            </g>
        </svg>
    );
};

const whichDayData: number[] = [21, 30, 100, 365];

export const startDayData = [
    { key: "0", label: "今天" },
    { key: "1", label: "明天" },
    { key: "2", label: "后天" },

];

export default function AddFlag({ isOpen, onClose }: { isOpen: boolean, onClose: () => void }) {

    const [whichDayButton, setWhichDayButton] = useState<number>(0)

    const [customPeriod, setCustomPeriod] = useState<number>(0)

    const [selected, setSelected] = useState<string[]>(['1']);

    const [description, setDescription] = useState<string>('')

    const [startDay, SetStartDay] = useState<number>(0);

    const [checktime, setCheckTime] = useState<TimeValue | null>();

    const [isOpenDescription, setIsOpenDescription] = useState(false);

    const [isOpenCheckTime, setIsOpenCheckTime] = useState(false);

    const [iconValue, setIconValue] = useState<number>(0x1F600)

    // reset state
    const resetState = () => {
        setWhichDayButton(0)
        setCustomPeriod(0)
        setSelected(['1'])
        setDescription('')
        SetStartDay(0)
        setCheckTime(null)
        setIsOpenDescription(false)
        setIsOpenCheckTime(false)
        setIconValue(0x1F600)
    }

    const { flags } = useAppSelector(selectFlagDetail)
    const { email } = useAppSelector(selectUserDetail)

    const handleSelectionChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        if (e.target.value == "") {
            SetStartDay(startDay)
        } else {
            SetStartDay(Number(e.target.value.replace(/[^0-9]/g, '')));
        }
    };

    const dispatch = useAppDispatch()

    // const computedDayCount = () => {
    //     const st = new Date("2025-01-25 22:14:56")
    //     const et = new Date("2025-02-15 22:14:56")
    //     const result = et.getTime() - st.getTime()
    //     console.log(result / (1 * 24 * 60 * 60 * 1000))
    // }

    const handleTimeInputChange = (e: TimeValue | null) => {
        setCheckTime(e);
    }

    const setPeriod = (i: number) => {
        setCustomPeriod(0)
        setWhichDayButton(i)
    }

    const setMode = (v: string[]) => {
        if (v.length === 0) {
            setSelected(['1'])
        } else {
            setSelected(v)
        }
    }

    const onlyNumber = (value: string): number => {
        return Number(value.replace(/[^0-9]/g, '')) > 365 ? 365 : Number(value.replace(/[^0-9]/g, ''))
    }

    const startDayCompute = (startDay: number,): string => {
        const date = new Date();
        date.setDate(date.getDate() + startDay);
        const time = date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
        return time.replaceAll("/", "-")
    }

    const periodDayCompute = (startDay: number, period: number): string => {
        const date = new Date();
        date.setDate(date.getDate() + startDay + period);
        const time = date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
        return time.replaceAll("/", "-")
    }

    const timeIsExpired = (checktime: TimeValue | null, startDate: string): boolean => {
        if (startDay > 0) return false
        const st = new Date(startDate)
        const ct = new Date()
        ct.setHours((checktime as Time)?.hour ?? 0)
        ct.setMinutes((checktime as Time)?.minute ?? 0)
        return st.getTime() > ct.getTime()
    }

    const checktimeCompute = (time: TimeValue | null): string => {
        const ct = new Date()
        ct.setHours((time as Time)?.hour ?? 0)
        ct.setMinutes((time as Time)?.minute ?? 0)
        ct.setSeconds(0)
        return ct.toLocaleTimeString("zh-CN", { timeZone: "Asia/Shanghai" })
    }

    const addFlag = async () => {
        const flag: AddFlagParams = {
            flag_id: flags.length + 1,
            start: startDayCompute(startDay),
            over: false,
            list: [],
            emoji: iconValue,
        }

        // 描述校验
        if (description === '') {
            return setIsOpenDescription(true)
        } else {
            flag.description = description;
        }
        // 周期校验
        if (customPeriod === 0) {
            flag.period = periodDayCompute(startDay, whichDayData[whichDayButton])
        } else {
            flag.period = periodDayCompute(startDay, customPeriod)
        }
        // 打卡时间校验
        if (!timeIsExpired(checktime ?? null, flag.start as string)) {
            flag.checktime = checktimeCompute(checktime ?? null)
        } else {
            if (checktime != undefined) {
                return setIsOpenCheckTime(true)
            }
        }
        // 模式校验
        if (selected.length === 0) {
            return console.log("mode is empty");
        } else {
            flag.mode = Number(selected[0]);
        }
        // 邮件校验
        if (email === '') {
            return console.log("email is empty");
        } else {
            flag.email = email;
        }
        const result = await createFlag(flag)
        if (result.code == 200) {
            toast.success(result.message);
            dispatch(updateFlagData(flag))
        } else {
            toast.error(result.message);
        }
        resetState()
        onClose()
    }

    const content = (v: string) => {
        return (
            <>
                <PopoverContent>
                    <span className="text-white">{v}</span>
                </PopoverContent>
            </>
        )
    }

    return (
        <>

            <Modal backdrop={"blur"} isDismissable={false} isOpen={isOpen} onClose={onClose} scrollBehavior="inside" placement="center">
                <ModalContent>
                    <>
                        <ModalHeader className="flex flex-row items-center gap-1">
                            <Button isIconOnly className="mr-1" color="secondary" size="md" radius="md" onPress={() => setIconValue(getRandomEmoji())}><span className="text-3xl">{unicodeToEmoji(iconValue)}</span></Button>
                            <span className="text-white">Create your flag ✨</span>
                        </ModalHeader>
                        <ModalBody>
                            <div className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4 text-white">
                                <Popover color="danger" isOpen={isOpenDescription} onOpenChange={() => setIsOpenDescription(false)} showArrow backdrop={"transparent"} offset={10} placement="bottom">
                                    <PopoverTrigger>
                                        <Textarea size="sm" value={description} onValueChange={(v) => setDescription(v)} label="Description" placeholder="Enter a description of your plan." />
                                    </PopoverTrigger>
                                    {content("Please enter a description of your plan.")}
                                </Popover>
                            </div>

                            <p className="text-white">Keep time</p>
                            <div className="flex w-full flex-nowrap md:flex-nowrap mb-6 md:mb-0 gap-4 text-white">
                                <ButtonGroup>
                                    <Button isIconOnly className="w-14" size="sm" variant={whichDayButton === 0 && customPeriod === 0 ? "solid" : "ghost"} onPress={() => setPeriod(0)} color="warning">{whichDayData[0]}天</Button>
                                    <Button isIconOnly className="w-14" size="sm" variant={whichDayButton === 1 && customPeriod === 0 ? "solid" : "ghost"} onPress={() => setPeriod(1)} color="warning">{whichDayData[1]}天</Button>
                                    <Button isIconOnly className="w-14" size="sm" variant={whichDayButton === 2 && customPeriod === 0 ? "solid" : "ghost"} onPress={() => setPeriod(2)} color="warning">{whichDayData[2]}天</Button>
                                    <Button isIconOnly className="w-14" size="sm" variant={whichDayButton === 3 && customPeriod === 0 ? "solid" : "ghost"} onPress={() => setPeriod(3)} color="warning">{whichDayData[3]}天</Button>
                                </ButtonGroup>
                                <Input
                                    size="sm"
                                    className="w-full text-sm"
                                    color="warning"
                                    placeholder="Custom"
                                    type="text"
                                    value={`${customPeriod === 0 ? "" : customPeriod}`}
                                    onValueChange={(value) => setCustomPeriod(onlyNumber(value))}
                                    name="period"
                                    endContent={
                                        <div className="pointer-events-none flex items-center">
                                            <span className="text-small" style={{ color: "#f9c97c" }}>天</span>
                                        </div>
                                    }
                                />
                            </div>

                            <div className="flex w-full flex-nowrap md:flex-nowrap mb-6 md:mb-0 gap-4 text-white">
                                <Select
                                    color={"warning"}
                                    label="Start Date"
                                    placeholder="Select an start day"
                                    name="start"
                                    size="sm"
                                    value={startDay}
                                    selectedKeys={[startDay + '']}
                                    onChange={handleSelectionChange}
                                    defaultSelectedKeys={['0']}
                                >
                                    {startDayData.map((v) => (
                                        <SelectItem className="text-white" key={v.key} value={v.key}>{v.label}</SelectItem>
                                    ))}
                                </Select>
                                <Popover color="danger" isOpen={isOpenCheckTime} onOpenChange={() => setIsOpenCheckTime(false)} showArrow backdrop={"transparent"} offset={10} placement="bottom">
                                    <PopoverTrigger>
                                        <TimeInput
                                            size="sm"
                                            className="max-w-[140px]"
                                            color="warning"
                                            label="Clockin Time"
                                            labelPlacement="inside"
                                            hourCycle={24}
                                            name="checktime"
                                            onChange={handleTimeInputChange}
                                            value={checktime}
                                            startContent={
                                                <ClockCircleLinearIcon className="text-xl text-default-400 pointer-events-none flex-shrink-0" />
                                            }
                                        />
                                    </PopoverTrigger>
                                    {content("Time has expired.")}
                                </Popover>

                            </div>

                            <div className="flex w-full flex-wrap md:flex-nowrap mb-6 md:mb-0 gap-4 text-white">
                                <CheckboxGroup
                                    color="warning"
                                    label={<span className="text-white">Clockin mode</span>}
                                    value={selected}
                                    onValueChange={(v) => setMode(v)}
                                    name="mode"
                                    orientation="horizontal"
                                    defaultValue={['1']}
                                >
                                    <Checkbox value={'1'}>default</Checkbox>
                                </CheckboxGroup>
                            </div>
                        </ModalBody>
                        <ModalFooter>
                            <Button color="danger" variant="light" onPress={() => onClose()}>
                                Cancel
                            </Button>
                            <Button color="primary" onPress={() => addFlag()}>
                                Add
                            </Button>
                        </ModalFooter>
                    </>
                </ModalContent>
            </Modal>
        </>
    );
}

